package cn.otrue.patienthealthmanager.xmpp;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;

import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import cn.otrue.patienthealthmanager.HealthApplication;
import cn.otrue.patienthealthmanager.activity.DoctorChatActivity;
import cn.otrue.patienthealthmanager.activity.MainActivity;
import cn.otrue.patienthealthmanager.bean.ChatModle;
import cn.otrue.patienthealthmanager.bean.HistoryChat;
import cn.otrue.patienthealthmanager.db.DBTools;
import cn.otrue.patienthealthmanager.fragment.FindDoctorChatLogFragment;
import cn.otrue.patienthealthmanager.receiver.MyPushMessageReceiver;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.MyConst;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.sqlite.WhereBuilder;
import com.lidroid.xutils.exception.DbException;

public class XMPPListener implements ChatManagerListener, FileTransferListener {

	private Handler messageHandler = new Handler() {

		@Override
		public void handleMessage(android.os.Message msg) {
			((MainActivity) MyConst.activity).initNum();

		}

	};

	public void chatCreated(Chat chat, boolean arg1) {
		final DbUtils dbutils = DbUtils.create(HealthApplication.getInstance());
		chat.addMessageListener(new MessageListener() {
			public void processMessage(Chat arg0, Message msg) {
				String body = msg.getBody();
				if (!TextUtils.isEmpty(body)) {
					String user = msg.getFrom();
					Log.e("xmpp", "getFrom" + msg.getFrom());
					if (user.contains("@")) {
						user = user.substring(0, user.indexOf("@"));
					}

					if (MyConst.activity instanceof DoctorChatActivity) {
						if (user.contains(MyConst.IN_USER)) {
							// 获取用户、消息、时间、IN
							String[] args = new String[] {
									user,
									msg.getBody(),
									CommonUtil.getFormatDate("MM-dd_hh:mm:ss",
											new Date()), "0" };
							// 在handler里取出来显示消息
							android.os.Message message = ((DoctorChatActivity) MyConst.activity).messageHandler
									.obtainMessage();
							message.what = 1;
							message.obj = args;
							message.sendToTarget();

						} else {

						}
					} else {
						String Account = MyConst.getACCOUNT();
						// 登录用户
						StringUtils.parseName(MyConst.getACCOUNT());
						// 发送消息用户
						msg.getFrom();
						// 消息内容

						Log.e("xmppM", "body" + body);

						ChatModle chatModle = new ChatModle(user, "", Account,
								"", body, "", MyConst.CHAT_IN, new Date(), 0);

						try {
							HistoryChat chat = dbutils.findFirst(Selector
									.from(HistoryChat.class)
									.where("doctorUser", "=", user)
									.and(WhereBuilder.b("patientUser", "=",
											Account)));
							if (chat != null) {
								chat.setUnreadNum(chat.getUnreadNum() + 1);
								dbutils.update(chat);
							} else {
								HistoryChat newChat = new HistoryChat(Account,
										user, 1, body, MyConst.FILE_TXT,
										new Date(), 1);
								dbutils.save(newChat);
							}
							dbutils.save(chatModle);

							if (MyConst.activity instanceof MainActivity) {
								if (MyConst.fragment instanceof FindDoctorChatLogFragment) {
									((FindDoctorChatLogFragment) MyConst.fragment)
											.changeList();
								} else {
									messageHandler
											.sendMessage(new android.os.Message());
								}
							} else {
								Map<String, String> otherMap = new HashMap<String, String>();

								otherMap.put("from", msg.getFrom());
								MyPushMessageReceiver.showMessage(-1, "您有新的消息",
										body, otherMap);
							}

							// FindDoctorChatLogFragment.change(msg.getFrom());
						} catch (DbException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				}
			}
		});
	}

	@Override
	public void fileTransferRequest(final FileTransferRequest prequest) {

		String fromName = prequest.getRequestor();
		if (fromName.contains("@")) {
			fromName = fromName.substring(0, fromName.indexOf("@"));
		}

		File saveFile = new File(Environment.getExternalStorageDirectory()
				+ "/HealthManager/doctor/" + fromName + "/");

		if (!saveFile.exists()) {
			saveFile.mkdirs();
		}
		saveFile = new File(saveFile, prequest.getFileName());
		startSave(saveFile, fromName, prequest);

	}

	private void startSave(final File saveFile, final String fromName,
			final FileTransferRequest request) {

		final IncomingFileTransfer infiletransfer = request.accept();
		try {
			infiletransfer.recieveFile(saveFile);
			Timer timer = new Timer();
			TimerTask updateProgessBar = new TimerTask() {
				public void run() {

					if (infiletransfer.getAmountWritten() >= request
							.getFileSize()) {

						saveDB(fromName, saveFile.getAbsolutePath());

						cancel();
					} else if ((infiletransfer.getStatus() == FileTransfer.Status.error)
							|| (infiletransfer.getStatus() == FileTransfer.Status.refused)
							|| (infiletransfer.getStatus() == FileTransfer.Status.cancelled)
							|| (infiletransfer.getStatus() == FileTransfer.Status.complete)) {
						request.reject();
						cancel();
					}
				}

				private void saveDB(String userName, String filePath) {
					try {
						if (MyConst.activity instanceof DoctorChatActivity
								&& userName.contains(MyConst.IN_USER)) {

							android.os.Message message = new android.os.Message();
							message.what = 2;
							message.obj = filePath;
							((DoctorChatActivity) MyConst.activity).fileHandler
									.sendMessage(message);
						} else {

							int fileType = 0;
							if (filePath.substring(
									filePath.lastIndexOf(".") + 1)
									.equals("acc")) {
								fileType = MyConst.FILE_AAC;
							} else {
								fileType = MyConst.FILE_PNG;
							}
							String Account = MyConst.getACCOUNT();
							ChatModle ChatModle = new ChatModle(userName, "",
									Account, "", "", filePath, MyConst.CHAT_IN,
									new Date(), 100);
							DBTools.db.save(ChatModle);
							HistoryChat chat = DBTools.db.findFirst(Selector
									.from(HistoryChat.class)
									.where("doctorUser", "=", userName)
									.and(WhereBuilder.b("patientUser", "=",
											Account)));

							if (chat != null) {
								chat.setUnreadNum(chat.getUnreadNum() + 1);
								DBTools.db.update(chat);
							} else {
								HistoryChat newChat = new HistoryChat(Account,
										userName, 1, "", fileType, new Date(),
										1);
								DBTools.db.save(newChat);
							}

							if (!(MyConst.activity instanceof DoctorChatActivity)) {
								if (MyConst.fragment instanceof FindDoctorChatLogFragment) {
									((FindDoctorChatLogFragment) MyConst.fragment)
											.changeList();
								} else {
									messageHandler
											.sendMessage(new android.os.Message());
								}
							} else {

							}
						}

					} catch (DbException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}
			};
			timer.scheduleAtFixedRate(updateProgessBar, 10L, 10L);
		} catch (XMPPException e) {
			// 接收失败
		}
	}

	// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

}
